package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionJoinApplyMgr;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Protocol.C_UNION_DEAL_APPLY, desc = "处理加入申请")
public class CrossDealJoinApplyCmd extends CrossCommand {

    long playerId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        playerId = packet.getPlayerId();

        UnionProto.UnionDealJoinApplyReqMsg reqMsg = UnionProto.UnionDealJoinApplyReqMsg.parseFrom(packet.getBytes());
        boolean isAllRefuse = reqMsg.getIsAllRefuse();
        long applyUserId = reqMsg.getUserId();
        boolean isAgree = reqMsg.getIsAgree();

        CrossUnionMember member = CrossUnionMgr.getUnionMemberByUserId(playerId);

        // 判断权限 族长 副族长才有权限
        if(member == null || StringUtils.isNullOrEmpty(member.getUnionUid())){
            ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
            return;
        }

        if (CrossUnionMgr.hasApplyPassRole(member)) {
            if (isAllRefuse) {// 一键拒绝
                CrossUnionJoinApplyMgr.removeAllJoinApply(member.getUnionUid());
            } else {
                if (isAgree) {
                    CrossUserBaseInfo baseInfo = CrossUserMgr.getCrossUserBaseInfo(playerId);
                    ret = CrossUnionJoinApplyMgr.agreeJoinApply(baseInfo, member.getUnionUid(), applyUserId);
                } else {
                    ret = CrossUnionJoinApplyMgr.removeJoinApply(member.getUnionUid(), applyUserId);
                }
            }
        } else {
            ret = GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
        }


    }

    @Override
    public void sendData() {
        UnionProto.UnionDealJoinApplyRespMsg.Builder respMsg = UnionProto.UnionDealJoinApplyRespMsg.newBuilder();
        respMsg.setRet(ret);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_UNION_DEAL_APPLY, respMsg));
    }
}
